package org.example.autoactivationplugin;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.Set;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.lang.IgnitePredicate;

/**
 * Activate cluser when nodes whith all specified attributes values join topology.
 * 
 * @author user
 */
public class ActivateByNodeAttribute implements IgnitePredicate{

    private String attributeName;
    private Set<String> requredValues;

    /**
     * Constructor
     * @param attributeName Node's attribute name
     * @param requredValues List of values for node's attribute
     */
    public ActivateByNodeAttribute(String attributeName, Set<String> requredValues) {
        if (attributeName.isBlank()) {
            throw new IllegalArgumentException("attributeName must be set");
        }
        this.attributeName = attributeName;

        if (requredValues==null || requredValues.isEmpty()) {
            throw new IllegalArgumentException("requredValues must be set");
        }
        this.requredValues = requredValues;
    }

    @Override
    public boolean apply(Object e) {
        Collection<ClusterNode> nodes = (Collection<ClusterNode>) e;
        Set<String> missingNodes = new LinkedHashSet<>(requredValues);
        for (ClusterNode node : nodes) {
            String attributeValue = node.attribute(attributeName);
            missingNodes.remove(attributeValue);
            if (missingNodes.isEmpty()) {
                break;
            }
        }
        return missingNodes.isEmpty();
    }

}
